<template>
  <!--新增/编辑计划-->
  <vx-popup :title="dialogTitle" width="1000px" @close="cancelSubmit" :active.sync="dialogVisible" @confirmPopup="handleSubmit" @cancelPopup="cancelSubmit" clearable>
    <el-form :model="ruleForm"  ref="ruleForm" class="demo-ruleForm">
      <el-row  justify="space-between" :gutter="24">
        <el-col :span="8">
          <el-form-item label="计划名称:" prop="planName" :rules="{required: true, message: '请输入计划名称', trigger: 'change'}" label-width="95px">
            <el-input v-model="ruleForm.planName" placeholder="请输入计划名称" size="small" style="width:100%" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="起始时间 :" prop="startTime" label-width="95px":rules="{required: true, message: '请输入起始时间', trigger: 'change'}">
            <el-date-picker
              v-model="ruleForm.startTime"
              type="date"
              size="small"
              placeholder="请选择开始时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd"
              style="width: 165px"
              clearable
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="终止时间 :" prop="endTime" label-width="95px" :rules="{required: true, message: '请输入终止时间', trigger: 'change'}">
            <el-date-picker
              v-model="ruleForm.endTime"
              type="date"
              size="small"
              placeholder="请选择结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd"
              style="width: 165px"
              clearable
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row  justify="space-between" :gutter="24">
        <el-col :span="8">
          <el-form-item label="巡检周期 :" prop="planCycle" label-width="95px" :rules="{required: true, message: '请输入起始时间', trigger: 'change'}">
            <el-select  v-model="ruleForm.planCycle" @change="select(ruleForm.planCycle)" placeholder="请选择巡检周期" size="small" style="width: 100%" clearable>
              <el-option label="月" :value="0"></el-option>
              <el-option label="日" :value="1"></el-option>
              <el-option label="周" :value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划频率:" prop="planFrequency" :rules="{required: true, message: '请输入计划频率', trigger: 'change'}" label-width="95px">
            <el-input v-model="ruleForm.planFrequency" placeholder="请输入计划频率" size="small" style="width: 165px" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="负责人 :" :rules="{ required: true, message: '请选择负责人', trigger: 'change' }" label-width="95px">
            <el-select
              filterable
              v-model="ruleForm.inspFirstPerson"
              placeholder="请选择负责人"
              size="small"
              collapse-tags
              style="width: 165px"
              clearable
            >
              <el-option v-for="item in responsiblePerson" :key="item.realId" :label="item.name" :value="+item.realId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row  justify="space-between" :gutter="24">
        <el-col :span="8">
          <el-form-item label="巡检小组 :" :rules="{ required: true, message: '请选择巡检小组', trigger: 'change' }" label-width="95px">
            <el-select
              filterable
              v-model="ruleForm.inspGroup"
              placeholder="请选择巡检小组"
              @change="(event) => changeitemGroup(event)"
              size="small"

              collapse-tags
              style="width: 200px"
              clearable
            >
              <el-option v-for="item in personGroup" :key="item.realId" :label="item.name" :value="+item.realId"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="巡检人员 :" :rules="{ required: true, message: '请选择巡检人员', trigger: 'change' }" label-width="95px">
            <el-select
              filterable
              v-model="ruleForm.inspPerson"
              placeholder="巡检人员(可多选)"
              size="small"
              multiple
              collapse-tags
              style="width: 165px"
              clearable
            >
              <el-option v-for="item in inspectionPersons" :key="item.realId" :label="item.name" :value="+item.realId"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row  justify="space-between" :gutter="24">
        <el-col :span="24">
          <el-form-item style="margin-top: -15px; margin-left: 8px" label="范围描述:" prop="routeScopeDecription" :rules="{ required: true, message: '请输入描述范围', trigger: 'change' }">
            <el-input
              type="textarea"
              v-model.trim="ruleForm.routeScopeDecription"
              maxlength="500"
              show-word-limit
              size="small"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row  justify="space-between" :gutter="24">
     <!--   :rules="{ required: true, message: '请选择巡检路线', trigger: 'change' }"-->
        <el-col :span="8">
          <el-form-item label="巡检路线 :" prop="inspRouteName"  label-width="95px">
            <el-select
              filterable
              v-model="ruleForm.inspRouteName"
              placeholder="请选择巡检路线"
              size="small"
              collapse-tags
              style="width: 165px"
              clearable
            >
              <el-option v-for="item in inspRoutes" :key="item.realId" :label="item.name" :value="item.name"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="24">
          <el-form-item label="巡检关键点:" style="margin-left: 10px">
            <el-table :data="tableData" stripe :header-cell-style="{
          background: '#8595B9',
          color: '#fff',
          height: '44px',
        }" max-height="660px">
              <el-table-column type="index" width="50"></el-table-column>
              <el-table-column prop="bridgeId" label="关键点名称" show-overflow-tooltip></el-table-column>
              <el-table-column property="keyPointsNumber" label="关键点编号" show-overflow-tooltip></el-table-column>
              <el-table-column property="inspObject" label="巡检对象" show-overflow-tooltip></el-table-column>
              <el-table-column property="clockMode" label="打卡方式" show-overflow-tooltip></el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>-->
     <!-- <el-row>
        <el-col :span="24">
          <el-form-item label="巡检路线:" style="margin-left: 10px">
            <div class="map_box" id="mapContaion">
            </div>
          </el-form-item>
        </el-col>
      </el-row>-->
    </el-form>
  </vx-popup>
</template>

<script>

  var numbersRules = (value, callback) => {
    var reg = /^[1-9]\d*$/
    if (value != null && value != '') {
      if (!reg.test(value)) {
        callback(new Error('请输入整数,值范围在0-1000000000之间!'))
      } else {
        callback()
      }
    } else {
      callback()
    }
  }

  export default {
    data() {
      return {
        dialogTitle: '新增计划',
        dialogVisible: false,
        responsiblePerson: [],
        personGroup: [],
        groupId: 1,
        inspectionPersons: [],
        inspRoutes: [],

        ruleForm: {
          planName:"",
          startTime:"",
          endTime:"",
          planCycle:null,
          planFrequency:null,
          inspFirstPerson:null,
          inspGroup:null,
          inspPerson:[],
          inspRouteBridges:[1,2,3],
          temporarySave:0,
          routeScopeDecription:"",
          inspRouteName:"",
          inspKeyPointsVos:[{
            "bridgeId":0,
            "keyPointsNumber":"001",
            "inspObject":"桥名牌",
            "clockMode":0
          }]
        },
       /* ruleForm: {
          planName:"",
          startTime:"",
          endTime:"",
          planCycle:1,
          planFrequency:1,
          inspFirstPerson:1,
          inspGroup:1,
          inspPerson:[],
          inspRouteBridges:[],
          temporarySave:0,
          routeScopeDecription:"",
          inspRouteName:"",
          inspKeyPointsVos:[{
            "bridgeId":0,
            "keyPointsNumber":"",
            "inspObject":"",
            "clockMode":0
          }]
        },*/
      }
    },

    created() {

    },

    mounted() {},
    methods: {
      //这里是点击巡检小组获取相对应的巡检人员
      changeitemGroup(event) {
        console.log('eventeventevent',event);
        const _parmas = {
          groupId: event
        }
        //巡检人员
        this.$api.insp.findAddPersonDropBox(_parmas).then((response) =>{
          if(response.data.code === 200){
            this.inspectionPersons = response.data.data.map((item, index)=> ({
              realId: item.uid,
              name: item.uname
            }))
          }
        })
      },
      //这个是获取负责人、巡检小组、巡检路线的接口
      inspPlanPageDropBox() {
        this.$api.insp.findAddDropBox().then((response) => {
           if(response.data.code ===200){
             console.log('111111111response.data.data',response.data.data);
             this.responsiblePerson = response.data.data.inspFirstPersons.map((item, index)=> ({
                realId: item.uid,
                name: item.uname
              }))
             this.personGroup = response.data.data.inspGroups.map((item,index) => ({
               realId: item.id,
               name: item.group_name
             }))
             this.inspRoutes = response.data.data.inspRoutes.map((item,index) => ({
               realId: item.id,
               name: item.insp_route_name
             }))
           }
        })
      },


      //父组件过来的add方法
      add(){
        this.dialogTitle = '新增计划'
        this.dialogVisible = true
        this.inspPlanPageDropBox()
        this.emptyForm()
      },
      /*emptyForm() {
        this.ruleForm= {
            planName: '',
            startTime: '',
            endTime: '',
            planCycle: 1,
            planFrequency: 1,
            inspFirstPerson: '',
            inspGroup: 1,
            inspPerson: [],
            inspRouteBridges: [],
            routeScopeDecription: '',
            inspRouteName: '',
            inspKeyPointsVos: {},
            bridgeId: 1,
            keyPointsNumber: '',
            inspObject: '',
            clockMode: 1,
            temporarySave: 0,
        }
      },*/
      //巡检的周期
      select(num) {
        console.log(num, 'num')
        if (num == 0) {
          this.type = '月'
        } else if (num == 1) {
          this.type = '日'
        } else {
          this.type = '周'
        }
      },
      resetRuleForm() {

      },
      //取消
      cancelSubmit() {
        this.dialogVisible =false
        this.resetRuleForm()
      },
      //确定
      handleSubmit() {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            if (this.dialogTitle === '新增计划') {
              let _params = this.ruleForm;
              _params.planFrequency = Number(_params.planFrequency)
              this.$api.insp.addInspPlan({...this.ruleForm}).then((response) =>{
                if (response.data.code === 200) {
                  this.$vs.notify({
                    text: '新增计划成功',
                    color: 'success',
                  })
                  this.dialogVisible = false
                  /*this.emptyForm()*/
                  this.addtitle = ''
                  this.$parent.queryForPage()
                }
              })
            }
            else {

            }
          } else {
            return false
          }
        })
      },














    /*  add() {
        ;(this.fagle = false), (this.dialogVisible = true)

        this.editId = null
        this.emptyForm()
      },*/
/*      edit(val) {
        this.$refs['ruleForm'].resetFields()
        ;(this.fagle = true), (this.dialogVisible = true)
        this.dialogTitle = '计划详情'
        this.editId = val
        this.queryPlanById(val)
      },
      emptyForm() {
        this.$refs['ruleForm'].resetFields()
        const emptyObj = {
          name: '',
          inspType: '',
          type: '',
          month: '',
          day: '',
          cron: '',

          inspBridges: [
            {
              bridge: '',
              name: [],
              inspStandard: '',
              itemUserList: [],
            },
          ],
        }
        this.ruleForm = emptyObj
      },
      queryBridgeList() {
        this.$api.bridge.AllTheBridges().then((response) => {
          if (response.data.success) {
            console.log(response.data, 'bridgeOptions')
            this.bridgeOptions = response.data.data[0]
          }
        })
      },
      changetime(e) {
        console.log(e, 'time')
      },
      queryPlanById(val) {
        this.fagle = true
        this.$api.insp.queryPlanById(val).then((response) => {
          const _data = response.data.data
          console.log(response.data.data, 'jihua')
          this.ruleForm.bridgeList.push(_data.name)
          this.ruleForm.itemUserList.push(_data.itemUserList)
          this.ruleForm.type = _data.type
          this.ruleForm.cycle = _data.cycle
          this.ruleForm.inspType = _data.inspType
          this.ruleForm.inspStandard = _data.inspStandard
          this.ruleForm.itemUserList = []
          _data.itemUserList.map((item) => {
            console.log(item.userName, '_datauserName')
            this.ruleForm.itemUserList.push(item.userName)
          })
          // console.log(this.ruleForm.itemUserList, '_data.itemUserList')
          this.ruleForm.execTime = [_data.beginExec, _data.endExec]
          if (_data.type == 0) {
            this.type = '月'
          } else if (_data.type == 1) {
            this.type = '日'
          } else {
            this.type = '周'
          }


        })
      },*/
      // handleAddLine() {
      //   this.ruleForm.inspBridges.push({
      //     bridge: '',
      //     name: [],
      //     inspStandard: '',
      //     itemUserList: [],
      //   })
      // },
      // handleDeleteItem(item, index) {
      //   this.ruleForm.inspBridges.splice(index, 1)
      // },
     /* handleSubmit() {
        console.log('111')
        this.$refs.ruleForm.validate(async (valid) => {
          if (!valid) {
            return false
          }
          // 巡检人id name传值处理
          let arr = []
          this.ruleForm.itemUserList.map((item) => {
            arr.push({
              orgId: null,
              orgName: null,
              userId: item.split(';')[0],
              userName: item.split(';')[1],
            })
          })
          // 桥梁传值id bridgeName传值处理
          this.bridgeArrS = []
          this.ext1Data.map((item) => {
            this.bridgeArrS.push({
              bridgeId: item.id,
              bridgeName: item.name,
              ext1: JSON.stringify({
                id: item.id,
                name: item.name,
                lng: item.lng,
                lat: item.lat,
                bridgeTypeId: item.bridgeTypeId,
                bridgeTypeName: item.bridgeTypeName,
                province: item.provinceName,
                city: item.municipalityName,
                area: item.regionName,
                standardName: item.standardName,
              }),
              inspPlanCfgPos: {
                ownId: item.id,
                ownName: item.name,
                lon: item.lng,
                lat: item.lat,
              },
            })
          })

          console.log(this.ruleForm.bridgeList)

          let _userInfo = JSON.parse(localStorage.getItem('userInfo'))
          // let _itemList = this.ruleForm.inspBridges.map((item) => {
          //   let _itemUserList = item.itemUserList.map((temp) => ({
          //     userId: temp.split(';')[0],
          //     userName: temp.split(';')[1],
          //   }))
          //   let _ext1 = {
          //     // ...item.bridge,
          //     id: item.bridge['id'] || '',
          //     name: item.bridge['name'] || '',
          //     lng: item.bridge['lng'] || '',
          //     lat: item.bridge['lat'] || '',
          //     bridgeTypeId: item.bridge['bridgeTypeId'] || '',
          //     bridgeTypeName: item.bridge['bridgeTypeName'] || '',
          //     province: item.bridge['provinceName'] || '',
          //     city: item.bridge['municipalityName'] || '',
          //     area: item.bridge['regionName'] || '',
          //     standardName: item.bridge['standardName'] || '',
          //   }

          //   return {
          //     name: item.name.length > 0 ? `${item.name[0].split(';')[1]}/${item.name[1].split(';')[1]}` : '',
          //     constructionId: item.name.length > 0 ? item.name[0].split(';')[0] : '',
          //     constructionName: item.name.length > 0 ? item.name[0].split(';')[1] : '',
          //     partsId: item.name.length > 0 ? item.name[1].split(';')[0] : '',
          //     partsName: item.name.length > 0 ? item.name[1].split(';')[1] : '',
          //     ownId: item.bridge['id'] || '',
          //     ownName: item.bridge['name'] || '',
          //     inspPlanCfgPos: {
          //       ownId: item.bridge['id'] || '',
          //       ownName: item.bridge['name'] || '',
          //       lon: item.bridge['lng'] || '',
          //       lat: item.bridge['lat'] || '',
          //     },
          //     inspStandard: parseInt(item.inspStandard),
          //     // itemUserList: _itemUserList,
          //
          //   }
          // })
          let _endExec = this.ruleForm.execTime[1].substring(0, 10)
          console.log(_endExec)
          let _params = {
            createUserId: _userInfo['userid'] || '',
            createUserName: _userInfo['realname'] || '',
            // name: this.ruleForm.name,
            inspType: this.ruleForm.inspType,
            type: this.ruleForm.type,
            cycle: parseInt(this.ruleForm.cycle),
            beginExec: this.ruleForm.execTime[0],
            endExec: `${_endExec} 23:59:59`,
            // validStartTime: this.ruleForm.validTime[0],
            // validEndTime: this.ruleForm.validTime[1],
            inspStandard: this.ruleForm.inspStandard,
            bridgeList: this.bridgeArrS,
            itemUserList: arr,
          }

          if (this.editId) {
            _params.id = this.editId
          }

          if (this.editId) {
            this.dialogVisible = false
            this.$emit('closeAddInspPlan')
            // this.$api.insp.updatePlan(_params).then((response) => {
            //   if (response.data.success) {
            //     this.$vs.notify({
            //       text: '修改成功',
            //       color: 'success',
            //       icon: 'success',
            //     })
            // this.dialogVisible = false
            // this.$emit('closeAddInspPlan')

            //   }
            // })
          } else {
            this.$api.insp.addPlan(_params).then((response) => {
              if (response.data.success) {
                this.$vs.notify({
                  text: '新增成功',
                  color: 'success',
                  icon: 'success',
                })
                this.bridgeArrS = []
                this.ext1Data = []
                this.dialogVisible = false
                this.$emit('closeAddInspPlan')
              }
            })
          }
        })
      },*/
     /* cancelSubmit() {
        this.dialogVisible = false
        this.ruleForm.bridgeList = []
        this.ruleForm.itemUserList = []
        this.ruleForm.type = ''
        this.ruleForm.cycle = ''
        this.ruleForm.inspType = ''
        this.ruleForm.inspStandard = ''
      },*/
     /* queryPersonList(pageIndex) {
        if (pageIndex && pageIndex === 1) {
          this.currentPage_sel = 1
        }
        const _params = {
          pageSize: this.pagesize_sel,
          pageNum: this.currentPage_sel,
          type: '0',
        }
        this.$api.personManager.getPersonList(_params).then((response) => {
          if (response.data.success) {
            this.personOptions = response.data.data
            //console.log(this.personOptions, 'this.personOptions')
            this.recordsTotal_sel = response.data.recordsTotal
          }
        })
      },*/
     /* handlePageChange_sel(currentPage) {
        this.currentPage_sel = currentPage
        this.queryPersonList()
      },
      changeUserList(e) {
        // console.log(e)
        // var arr = []
        // e.map((item) => {
        //   arr.push({
        //     orgId: null,
        //     orgName: null,
        //     userId: item.split(';')[0],
        //     userName: item.split(';')[1],
        //   })
        // })
        // // 组件方法有重复数据去重
        // var obj = {}
        // for (var i = 0; i < arr.length; i++) {
        //   if (!obj[arr[i].key]) {
        //     this.itemUserList.push(arr[i])
        //     obj[arr[i].key] = true
        //   }
        // }
      },
      handleBridgeChange(event, index) {
        this.ext1Data = []
        console.log(this.ext1Data, 'this.ext1Data.push')
        let bridgeId = ''
        let bridgeArr = event.map((item) => {
          return item.slice(0, 18)
        })

        console.log(bridgeArr, 'bridgeArr')
        this.bridgeOptions.map((item) => {
          bridgeArr.map((temp) => {
            if (item.id == temp) {
              this.ext1Data.push(item)
            }
          })
        })

        const _params = {
          bridgeTypeId: event['bridgeTypeId'] || '',
          pId: '-1',
          bridgeId: event['id'] || '',
        }
        this.queryConstructionModelTreeById(_params, index)
      },
      handleChangeDeasePos(event, index) {},
      deepDeasePosOptions(data) {
        let _arr = []
        let _obj = {}
        data.map((item) => {
          const _tmp = {
            ...item,
          }
          if (_tmp.children && _tmp.children.length > 0) {
            _tmp.children = this.deepDeasePosOptions(_tmp.children)
          }
          _obj = {
            id: _tmp.id,
            name: _tmp.name,
            value: `${_tmp.id};${_tmp.name}`,
          }
          if (_tmp.children && _tmp.children.length > 0) {
            _obj.children = _tmp.children
          }
          _arr.push(_obj)
        })
        return _arr
      },
      queryConstructionModelTreeById(_params, index) {
        this.$api.bridge.queryConstructionModelTreeById(_params).then((response) => {
          if (response.data.success) {
            ++this.isResouceShow
            this.deasePosOptions[index] = this.deepDeasePosOptions(response.data.data.children)
          }
        })
      },
      createNumberOptions(length, unit) {
        let _options = []
        for (let i = 0; i < length; i++) {
          _options.push({
            label: `${i + 1}${unit}`,
            value: i + 1,
          })
        }
        return _options
      },*/
    },
  }
</script>
<style lang="scss" scoped>
  @import '@/assets/scss/baseColor.scss';
  @import '../insp.scss';
</style>





